<template>
  <div class="statistics-container">
    <!-- 顶部标签页 -->
    <el-tabs v-model="activeTab" class="statistics-tabs" @tab-change="handleTabChange">
      <el-tab-pane label="设备统计" name="device">
        <!-- 设备统计汇总卡片 -->
        <div class="summary-cards">
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon device-icon">
                <el-icon :size="32"><Monitor /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ deviceSummary.total_devices }}</div>
                <div class="card-label">设备总数</div>
              </div>
            </div>
          </el-card>
          
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon count-icon">
                <el-icon :size="32"><Histogram /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ deviceSummary.total_usage_count }}</div>
                <div class="card-label">总使用次数（次）</div>
              </div>
            </div>
          </el-card>
          
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon volume-icon">
                <el-icon :size="32"><DataAnalysis /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ deviceSummary.total_usage_volume }}</div>
                <div class="card-label">总使用量（L）</div>
              </div>
            </div>
          </el-card>
          
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon avg-icon">
                <el-icon :size="32"><TrendCharts /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ deviceSummary.avg_usage_count }}</div>
                <div class="card-label">平均使用次数（次）</div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 设备统计表格 -->
        <el-card class="table-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">设备使用详情</span>
              <el-button type="primary" :icon="Download" size="small">导出数据</el-button>
            </div>
          </template>
          
          <el-table 
            :data="deviceList" 
            v-loading="deviceLoading"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="device_id" label="设备ID" width="120" />
            <el-table-column prop="device_name" label="设备名称" width="150" />
            <el-table-column prop="usage_count" label="使用次数（次）" width="140" sortable>
              <template #default="scope">
                <el-tag type="primary">{{ scope.row.usage_count }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="usage_volume" label="使用量（L）" width="140" sortable>
              <template #default="scope">
                <el-tag type="success">{{ scope.row.usage_volume }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="avg_volume_per_use" label="平均每次使用量（L）" width="180" />
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="病床统计" name="bed">
        <!-- 病床统计汇总卡片 -->
        <div class="summary-cards">
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon bed-icon">
                <el-icon :size="32"><House /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ bedSummary.total_beds }}</div>
                <div class="card-label">病床总数</div>
              </div>
            </div>
          </el-card>
          
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon occupied-icon">
                <el-icon :size="32"><User /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ bedSummary.occupied_beds }}</div>
                <div class="card-label">占用病床数</div>
              </div>
            </div>
          </el-card>
          
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon count-icon">
                <el-icon :size="32"><Histogram /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ bedSummary.total_usage_count }}</div>
                <div class="card-label">总使用次数（次）</div>
              </div>
            </div>
          </el-card>
          
          <el-card class="summary-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon volume-icon">
                <el-icon :size="32"><DataAnalysis /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ bedSummary.total_usage_volume }}</div>
                <div class="card-label">总使用量（L）</div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 按病房展开的病床统计 -->
        <el-card class="table-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">病床使用详情</span>
              <el-button type="primary" :icon="Download" size="small">导出数据</el-button>
            </div>
          </template>
          
          <div v-loading="bedLoading">
            <div v-for="ward in wardList" :key="ward.ward" class="ward-section">
              <div class="ward-header">
                <div class="ward-title">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ ward.ward }}</span>
                </div>
                <div class="ward-stats">
                  <el-tag type="info" size="small">
                    床位数: {{ ward.total_beds }}
                  </el-tag>
                  <el-tag type="success" size="small">
                    占用率: {{ ward.occupancy_rate }}%
                  </el-tag>
                  <el-tag type="primary" size="small">
                    使用次数: {{ ward.total_usage_count }}
                  </el-tag>
                  <el-tag type="warning" size="small">
                    使用量: {{ ward.total_usage_volume }}L
                  </el-tag>
                </div>
              </div>
              
              <el-table 
                :data="ward.beds" 
                stripe
                style="width: 100%"
                class="ward-table"
              >
                <el-table-column prop="bed" label="病床号" width="120" />
                <el-table-column prop="device_name" label="设备" width="150">
                  <template #default="scope">
                    <el-tag v-if="scope.row.device_id" type="success" size="small">
                      {{ scope.row.device_name }}
                    </el-tag>
                    <el-tag v-else type="info" size="small">未分配</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="usage_count" label="使用次数（次）" width="140" sortable>
                  <template #default="scope">
                    <el-tag type="primary">{{ scope.row.usage_count }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="usage_volume" label="使用量（L）" width="140" sortable>
                  <template #default="scope">
                    <el-tag type="success">{{ scope.row.usage_volume }}</el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Monitor, 
  Histogram, 
  DataAnalysis, 
  TrendCharts, 
  House, 
  User,
  Download,
  OfficeBuilding
} from '@element-plus/icons-vue'
import { getDeviceStatistics, getBedStatistics } from '@/api/statistics'
import { formatDateTime } from '@/utils/format'

const activeTab = ref('device')
const deviceLoading = ref(false)
const bedLoading = ref(false)

// 设备统计数据
const deviceSummary = reactive({
  total_devices: 0,
  total_usage_count: 0,
  total_usage_volume: 0,
  avg_usage_count: 0,
  avg_usage_volume: 0
})
const deviceList = ref([])

// 病床统计数据
const bedSummary = reactive({
  total_beds: 0,
  occupied_beds: 0,
  total_usage_count: 0,
  total_usage_volume: 0,
  occupancy_rate: 0
})
const wardList = ref([])

// 加载设备统计
const loadDeviceStatistics = async () => {
  deviceLoading.value = true
  try {
    const res = await getDeviceStatistics()
    if (res.code === 200) {
      // 更新汇总数据
      Object.assign(deviceSummary, res.data.summary)
      // 更新设备列表
      deviceList.value = res.data.devices
    } else {
      ElMessage.error(res.message || '加载设备统计失败')
    }
  } catch (error) {
    ElMessage.error('加载设备统计失败')
    console.error('加载设备统计失败:', error)
  } finally {
    deviceLoading.value = false
  }
}

// 加载病床统计
const loadBedStatistics = async () => {
  bedLoading.value = true
  try {
    const res = await getBedStatistics()
    if (res.code === 200) {
      // 更新汇总数据
      Object.assign(bedSummary, res.data.summary)
      // 更新病房列表
      wardList.value = res.data.wards
    } else {
      ElMessage.error(res.message || '加载病床统计失败')
    }
  } catch (error) {
    ElMessage.error('加载病床统计失败')
    console.error('加载病床统计失败:', error)
  } finally {
    bedLoading.value = false
  }
}

// 标签切换
const handleTabChange = (tabName) => {
  if (tabName === 'device' && deviceList.value.length === 0) {
    loadDeviceStatistics()
  } else if (tabName === 'bed' && wardList.value.length === 0) {
    loadBedStatistics()
  }
}

// 初始化
onMounted(() => {
  loadDeviceStatistics()
})
</script>

<style scoped>
.statistics-container {
  width: 100%;
  height: 100%;
}

.statistics-tabs {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

/* 汇总卡片 */
.summary-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.summary-card {
  border-radius: 8px;
  transition: transform 0.3s;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.card-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.card-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.device-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.count-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.volume-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.avg-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.bed-icon {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.occupied-icon {
  background: linear-gradient(135deg, #30cfd0 0%, #330867 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

/* 表格卡片 */
.table-card {
  border-radius: 8px;
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 病房分组 */
.ward-section {
  margin-bottom: 30px;
}

.ward-section:last-child {
  margin-bottom: 0;
}

.ward-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px 8px 0 0;
  color: #fff;
  margin-bottom: 0;
}

.ward-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
}

.ward-stats {
  display: flex;
  gap: 10px;
}

.ward-table {
  border-radius: 0 0 8px 8px;
  overflow: hidden;
}

:deep(.el-table) {
  border-radius: 0 0 8px 8px;
}

:deep(.el-table__header) {
  background: #f5f7fa;
}

:deep(.el-table th) {
  background: #f5f7fa;
}
</style>

